package com.zhuqi.netty.handler;

import cn.hutool.core.date.DateUtil;
import com.zhuqi.proto.HeartBeat;
import com.zhuqi.proto.build.HeatBeatProtoBuild;
import com.zhuqi.proto.cost.MessageProtocolBufEnum;
import com.zhuqi.session.messge.MessagePackage;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;


/**
 * <p>心跳消息返回</p>
 * @author zhuqi
 * @since 2023/3/10 14:19
 */
@Slf4j
public class HeartBeatHandler extends SimpleChannelInboundHandler<HeartBeat.HeartBeatRequest> {

	/**
	 * 客户端心跳 回应
	 * pong
	 */
	@Override
	protected void channelRead0(ChannelHandlerContext ctx, HeartBeat.HeartBeatRequest msg) {
		log.info("服务器心跳 msg:{}", msg.getName() + msg.getDatetime());
		String now = DateUtil.now();
		HeartBeat.HeartBeatRequest heartBeatRequest = HeatBeatProtoBuild
				.createHeartBeatRequest("client", now);
		MessagePackage messagePackage = new MessagePackage();
		messagePackage.setBusinessCode(MessageProtocolBufEnum.HEARTBEAT_REQUEST_MESSAGE.getCode());
		messagePackage.setData(heartBeatRequest.toByteArray());
		log.info("heartBeat:{}", now);
		ctx.writeAndFlush(messagePackage);
	}
}
